package com.mantru.iotpot.modbus;

import java.io.*;
import java.text.*;
import java.util.*;

public class RobotClientReadThread extends Thread
{
	private InputStream InStream;
	private int ReceiveSize;
	private byte[] ReceiveBuffer = new byte[1024];
	private byte[] RemainBuffer;
	private int Receive_Total_Length;
	private byte Receive_Command_Id;
	private RobotClientEventThread EventThread;
	private boolean Active;
	private int ClientID;

	public RobotClientReadThread(InputStream aStream, RobotClientEventThread aEventThread)
	{
		InStream = aStream;
		EventThread = aEventThread;
		ClientID = 1;
		Active = true;
	}

	@Override
	public void run()
	{
		while (Active)
		{
			try
			{
				ReceiveSize = InStream.read(ReceiveBuffer);
				if (ReceiveSize == -1)
				{
					if (Active)
					{
						Active = false;
						Log("RobotClientReadThread 读取网络异常");
						EventThread.SocketReadErrorCallBack();
					}
					break;
				}
				if (ReceiveSize > 0)
				{
					try
					{
						byte[] aBuffer = PeekBytesValue(ReceiveBuffer, 0, ReceiveSize);
						EventThread.ReceiveCallBack(aBuffer);
						aBuffer = null;
						System.gc();
					}
					catch(Exception e2)
					{}
				}
				Active = EventThread.Active;
				Thread.sleep(200);
			}
			catch(Exception e)
			{
				if (Active)
				{
					Log("RobotClientReadThread Run Error:" + e.getMessage());
					EventThread.SocketReadErrorCallBack();
					Active = false;
				}
			}
		}
		Log("RobotClientReadThread Run End");
		// this.stop();
	}

	//关闭线程
	public void Abort()
	{
		Active = false;
	}

	public void Log(String str)
	{
		Date nowDate = new Date();
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String log_str = "[" + format.format(nowDate) + "] socket-->" + str;

		System.out.println(log_str);
	}

	//返回收到的数据包中从index起始位置的count个字节
	public byte[] PeekBytesValue(byte[] bytes, int index, int count)
	{
		byte[] buffer = new byte[count];
		System.arraycopy(bytes, index, buffer, 0, count);
		return buffer;
	}
}
